package com.wenjie.original.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.wenjie.original.entity.Box;
import com.wenjie.original.entity.CodeList;
import com.wenjie.original.entity.table.CodeListTableDef;
import com.wenjie.original.flex_config.baseInterface.Cus_ServiceImp;
import com.wenjie.original.mapper.BoxMapper;
import com.wenjie.original.service.IBoxService;
import com.wenjie.original.service.ICodeListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 箱子信息  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-10 15:47:23
 */
@Service
public class BoxServiceImpl extends Cus_ServiceImp<BoxMapper, Box> implements IBoxService {


    @Autowired
    private ICodeListService codeListService;

    @Override
    public List<String> generateCode(Integer num) {
        return this.generate(num);
    }

    /**
     * @Description 生成条码 FM241011-1-1
     * @author wenjie
     * @date 2024/10/28 14:52
     */
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public synchronized List<String> generate(Integer num) {
        List<String> res = new ArrayList(num);

        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
        String dateStr = date.format(formatter);

        CodeList codeList = codeListService.getOne(QueryWrapper.create().orderBy(CodeListTableDef.CODE_LIST.CREATE_TIME.desc()));


        Integer flg = 1;
        if (codeList != null && codeList.getDate().equals(dateStr)) {
            flg = codeList.getFlg() + 1;
        }


        List<CodeList> codeLists = new ArrayList<>();
        for (Integer i = 1; i <= num; i++) {
            String code = "FM" + dateStr + "-" + flg.toString() + "-" + i.toString();
            res.add(code);

            CodeList codeList1 = new CodeList();
            codeList1.setCode(code);
            codeList1.setDate(dateStr);
            codeList1.setFlg(flg);
            codeLists.add(codeList1);
        }
        codeListService.saveBatch(codeLists);
        return res;
    }


}
